package nickthissen.iracing.activities;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.Toast;

import nickthissen.iracing.common.DataLoader;
import nickthissen.iracing.common.Task;
import nickthissen.iracing.common.Error;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.datamodels.User;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.Networking;
import nickthissen.iracing.parsing.HttpUtil;
import nickthissen.iracing.parsing.MessageParser;

public class PostActivity extends PostBaseActivity
{
    private static final String FORUM_ID = "FORUM_ID";
    private static final String THREAD_ID = "THREAD_ID";
    private static final String QUOTE_URL = "QUOTE_URL";
    private static final String EDIT_URL = "EDIT_URL";
    private static final String POST_ID = "POST_ID";
    private static final String TYPE = "TYPE";
    private static final String URL = "URL";

    private String storedUrl;
	private int forumId, threadId, postId;

	private ProgressDialog dialog;
		
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        txtTitle.setVisibility(View.GONE);
        txtUser.setVisibility(View.GONE);
        btnFindUser.setVisibility(View.GONE);

        txtContent.requestFocus();

        Bundle extras = savedInstanceState;
        if (extras == null)
        {
            Intent i = this.getIntent();
            extras = i.getExtras();
        }
        forumId = extras.getInt(FORUM_ID);
        threadId = extras.getInt(THREAD_ID);

        this.getSupportActionBar().setTitle("Write new post");

        if (type == PostBaseActivity.TYPE_QUOTE)
        {
            storedUrl = extras.getString(QUOTE_URL);
        	this.loadQuoteContents(storedUrl);
        }
        else if (type == PostBaseActivity.TYPE_EDIT)
        {
            storedUrl = extras.getString(EDIT_URL);
        	postId = extras.getInt(POST_ID);
        	this.loadEditContents(storedUrl);

            this.getSupportActionBar().setTitle("Edit post");
        }
    }
	
	@Override
	public void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
        outState.putInt(FORUM_ID, forumId);
        outState.putInt(THREAD_ID, threadId);
        outState.putInt(POST_ID, postId);
	}

    @Override
    public void onRestoreInstanceState(Bundle state)
    {
        forumId = state.getInt(FORUM_ID);
        threadId = state.getInt(THREAD_ID);
        postId = state.getInt(POST_ID);
        super.onRestoreInstanceState(state);
    }

    @Override
    protected Task<?> createTask()
    {
        return new Task<Integer>(this, messageLoader);
    }

    @Override
    protected void saveTaskInput(Bundle state)
    {
        state.putString(URL, storedUrl);
    }

    @Override
    protected Object restoreTaskInput(Bundle state)
    {
        return state.getString(URL);
    }

	private static Bundle getIntentExtras(int forumId, int threadId)
	{
		Bundle extras = new Bundle();
		extras.putInt(FORUM_ID, forumId);
		extras.putInt(THREAD_ID, threadId);
		return extras;
	}
	
	public static Intent getPostIntent(Context context, int forumId, int threadId)
	{
		Intent intent = new Intent(context, PostActivity.class);
		Bundle extras = getIntentExtras(forumId, threadId);
		extras.putInt(TYPE, PostActivity.TYPE_POST);
		intent.putExtras(extras);
		return intent;
	}
	
	public static Intent getQuoteIntent(Context context, int forumId, int threadId, String quoteUrl)
	{
		Intent intent = new Intent(context, PostActivity.class);
		Bundle extras = getIntentExtras(forumId, threadId);
		extras.putInt(TYPE, PostActivity.TYPE_QUOTE);
		extras.putString(QUOTE_URL, quoteUrl);
		intent.putExtras(extras);
		return intent;
	}
	
	public static Intent getEditIntent(Context context, int forumId, int threadId, int postId, String editUrl)
	{
		Intent intent = new Intent(context, PostActivity.class);
		Bundle extras = getIntentExtras(forumId, threadId);
		extras.putInt(TYPE, PostActivity.TYPE_EDIT);
		extras.putString(EDIT_URL, editUrl);
		extras.putInt(POST_ID, postId);
		intent.putExtras(extras);
		return intent;
	}
	
	private void loadQuoteContents(String url)
	{
        dialog = ProgressDialog.show(this, "Loading", "Loading quote contents...");
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(false);

        storedUrl = url;
        this.runTask(TYPE_QUOTE);

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
        {
            @Override
            public void onCancel(DialogInterface d)
            {
                task.cancel(true);
                d.dismiss();
            }
        });
	}
	
	private void loadEditContents(String url)
	{
        dialog = ProgressDialog.show(this, "Loading", "Loading edit contents...");
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(false);

        storedUrl = url;
        this.runTask(TYPE_EDIT);

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
        {
            @Override
            public void onCancel(DialogInterface d)
            {
                task.cancel(true);
                d.dismiss();
            }
        });
    }
	
	@Override
	protected void onPostButtonClicked()
	{
		dialog = ProgressDialog.show(this, "Posting", "Your message is being posted...");
		new Task<Void>(this, poster).execute();
	}

    private DataLoader<Integer> messageLoader = new DataLoader<Integer>()
    {
        @Override
        public Result getData(Integer in)
        {
            Result result;
            if (type == TYPE_QUOTE)
                result = Networking.getQuoteContents(this.getContext(), storedUrl);
            else
                result = Networking.getEditContents(this.getContext(), storedUrl);

            if (result.Success)
            {
                String source = (String)result.Object;
                return new MessageParser().parse(source);
            }
            else
            {
                return result;
            }
        }

        @Override
        public void onFinished(Result out)
        {
            String contents = "";
            if (out.Success)
            {
                contents = (String)out.Object;
            }
            else
            {
                Error.fromResult(out).report(this.getContext());
            }

            txtContent.setText(contents);

            if (dialog != null)
            {
                dialog.dismiss();
                dialog = null;
            }
        }
    };

    private DataLoader<Void> poster = new DataLoader<Void>()
    {
        @Override
        public Result getData(Void in)
        {
            String text = txtContent.getText().toString();

            text = HttpUtil.htmlEncode(text);

            if (type == PostBaseActivity.TYPE_EDIT)
            {
                return Networking.editMessage(this.getContext(), forumId, threadId, postId, text);
            }
            else
            {
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getContext());
                boolean attachSig = prefs.getBoolean(this.getContext().getString(R.string.PREF_AttachSignature), true);
                return Networking.postMessage(this.getContext(), forumId, threadId, text, attachSig);
            }
        }

        @Override
        public void onFinished(Result out)
        {
            if (out.Success)
            {
                Toast.makeText(this.getContext(),
                        "Message posted!",
                        Toast.LENGTH_LONG).show();
            }
            else
            {
                Error.fromResult(out).log(this.getContext());

                @SuppressWarnings("deprecation")
                ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboard.setText(txtContent.getText().toString());

                Toast.makeText(this.getContext(),
                        "Error posting message, please try again. Your message has been saved in your clipboard.",
                        Toast.LENGTH_LONG).show();
            }

            postFinished();

            if (dialog != null)
            {
                dialog.dismiss();
                dialog = null;
            }
        }
    };
}
